import 'package:flutter/material.dart';
import 'package:flutter_house_manager/pages/Home/index.dart';
import 'package:flutter_house_manager/pages/Mine/index.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  State<TabsPage> createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  // 底部导航栏
  final List _tabList = [
    {
      "label": '首页',
      "icon": "assets/tabs/home_default.png",
      "active_icon": "assets/tabs/home_active.png"
    },
    {
      "label": '我的',
      "icon": "assets/tabs/my_default.png",
      "active_icon": "assets/tabs/my_active.png"
    }
  ];

  // 返回底部Tabs中的item
  List<BottomNavigationBarItem> _getTabsBar() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabList) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(
            item['icon'],
            width: 30,
            height: 30,
          ),
          activeIcon: Image.asset(
            item['active_icon'],
            width: 30,
            height: 30,
          ),
          label: item['label']));
    }
    return list;
  }

  // 当前选中的索引
  int _currentIndex = 0;

  /// 注册事件
  registerEvent() {
    // 1. 401退出登录处理
    eventBus.on<LogoutEvent>().listen((event) {
      // PromptAction.showSuccess(event.msg);
      // 1.1 清除token
      tokenManager.removeToken();
      // 1.2 跳转登录页面
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  void initState() {
    super.initState();
    tokenManager.init();
    registerEvent();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: IndexedStack(
        index: _currentIndex,
        children: [
          const HomePage(),
          MinePage(currentIndex: _currentIndex),
        ],
      )),
      bottomNavigationBar: BottomNavigationBar(
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        items: _getTabsBar(),
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}
